# Files
HEADERS = $(wildcard include/*.h)
SRC = $(wildcard src/*.c)

# Project data
NAME = ddt_core
VERSION = 0.1.0
TARBALL = ${NAME}-${VERSION}.tar

# Compiler arguments
CC = cc
CFLAGS = -Wall -Wextra -pedantic -Iinclude

# shared/static data
DDIR = build-shared
SDIR = build-static
DOBJ = ${SRC:src/%.c=${DDIR}/%.o}
SOBJ = ${SRC:src/%.c=${SDIR}/%.o}
DOUT = lib/lib${NAME}.so
SOUT = lib/lib${NAME}.a

### Rules ###

# default rule
default: static

# compile both static and shared
all: shared static

# create shared library
shared: ${DOUT}
${DOUT}: ${DOBJ}
	@mkdir -p lib
	${CC} -shared -o $@ $^

# create static library
static: ${SOUT}
${SOUT}: ${SOBJ}
	@mkdir -p lib
	ar rcs $@ $^

# install (default)
install: install_static

# install shared library
install_shared: ${DOUT}
	@mkdir -p ${DESTDIR}${PREFIX}/include
	@install -m644 ${HEADERS} ${DESTDIR}${PREFIX}/include
	@echo installed headers in ${DESTDIR}${PREFIX}/include
	@mkdir -p ${DESTDIR}${PREFIX}/lib
	@install -m755 ${DOUT} ${DESTDIR}${PREFIX}/lib
	@echo installed library in ${DESTDIR}${PREFIX}/${DOUT}

# install static library
install_static: ${SOUT}
	@mkdir -p ${DESTDIR}${PREFIX}/include
	@install -m644 ${HEADERS} ${DESTDIR}${PREFIX}/include
	@echo installed headers in ${DESTDIR}${PREFIX}/include
	@mkdir -p ${DESTDIR}${PREFIX}/lib
	@install -m755 ${SOUT} ${DESTDIR}${PREFIX}/lib
	@echo installed library in ${DESTDIR}${PREFIX}/${SOUT}

# uninstall (default)
uninstall: uninstall_static

# uninstall shared library (default)
uninstall_shared:
	@rm -f ${HEADERS:%=${DESTDIR}${PREFIX}/%}
	@echo removed headers from ${DESTDIR}${PREFIX}/include
	@rm -f ${DESTDIR}${PREFIX}/${DOUT}
	@echo removed ${DESTDIR}${PREFIX}/${DOUT}

# uninstall static library
uninstall_static:
	@rm -f ${HEADERS:%=${DESTDIR}${PREFIX}/%}
	@echo removed headers from ${DESTDIR}${PREFIX}/include
	@rm -f ${DESTDIR}${PREFIX}/${SOUT}
	@echo removed ${DESTDIR}${PREFIX}/${SOUT}

# clean directory
clean:
	@-rm -rf ${DDIR} ${SDIR} lib
	@-rm -f ${TARBALL}
	@echo project cleaned

tarball:
	@tar -cf ${TARBALL} include/ src/ configure LICENSE Makefile.in README.md
	@echo \'${TARBALL}\' created

.PHONY : clean install uninstall tarball shared static

# Re-compile when any header changes
${DOUT} ${SOUT}: ${HEADERS}

# how to compile files for shared library
${DDIR}/%.o: src/%.c | ${DDIR}
	${CC} ${CFLAGS} -fPIC -o $@ -c $<

# how to compile files for static library
${SDIR}/%.o: src/%.c | ${SDIR}
	${CC} ${CFLAGS} -o $@ -c $<

# create folders
${DDIR}:
	mkdir ${DDIR}
${SDIR}:
	mkdir ${SDIR}
